<?
ini_set("display_errors",1);
include($_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php');
include($_SERVER['DOCUMENT_ROOT'].'/portals/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');

init_session();



include($_SERVER['DOCUMENT_ROOT'].'/portals/header.inc.php');

print "<h2>Visual similarity prototype</h2>";

if (empty($_GET['id']) || intval($_GET['id'] <= 1)) {

	$id = getOne("SELECT gridimage_id FROM libpuzzlesig LIMIT ".rand(0,5000).",1");
} else {
	$id = intval($_GET['id']);
}

$words = getCol("SELECT word FROM libpuzzleword WHERE gridimage_id = $id");

if (empty($words)) {
	die("image not in portal, or otherwise not found");
}


$images = getAssoc("SELECT gridimage_id,COUNT(*) c FROM libpuzzleword WHERE `word` IN (".implode(',',$words).") GROUP BY gridimage_id ORDER BY c DESC LIMIT 40");


if (empty($images) || count($images) < 2) {
	die("no similar images found - sorry");
}
if (count($images) == 40) {
	print "<p>Top 40 similar images shown. ";
	
} else {
	print "<p>".count($images)." image similar images found. ";
}

print " load <a href=\"?id=rand\">Another Random image</a>";

	$ids = array_keys($images);
		
	$imagedata = getAssoc("SELECT gridimage_id,grid_reference,title,realname,user_id FROM geograph_live.gridimage_search WHERE gridimage_id IN (".implode(',',$ids).")");
		
	foreach ($images as $gid => $count) {
		$c = $imagedata[$gid];
		if ($c) {
			$c['gridimage_id'] = $gid;
		?>
		  <div style="float:left;position:relative; width:150px; height:150px; padding:2px; text-align:center; border:1px solid silver">
		<?=$count ?>
		  <div align="center" style="width:120px;margin-left:auto;margin-right:auto" class="hoverimage" id="<? echo $id; ?>">
		  <a title="<? ehec('grid_reference'); ?> : <? ehec('title'); ?> by <? ehec('realname'); ?> - click to view full size image" href="http://www.geograph.org.uk/photo/<? echo $c['gridimage_id']; ?>" style="border:0"><img src="<? echo gGUc($c); ?>"/></a></div>
		  <a href="?id=<? echo $c['gridimage_id']; ?>">similar</a>
	 	 </div>
		<?
		}

	}
	print "<br style=\"clear:both\"/>";


	
	
include($_SERVER['DOCUMENT_ROOT'].'/portals/footer.inc.php');
